<template>
  <view class="share-group">
    <!-- #ifdef H5 -->
    <van-nav-bar @click-left="onClickLeft" left-arrow title="分享活动"></van-nav-bar>
    <!-- #endif -->
    <view class="share-group-bg" :style="heightScroll">
      <view
        class="share-group-img"
        v-if="data.pic"
        :style="{ backgroundImage: `url(${data.pic})` }"></view>
    </view>
    <!-- 底部按钮 -->
    <view class="bottom-wrap">
      <!-- #ifdef MP-WEIXIN -->
      <button class="bnt-wrap bnt" open-type="share">去分享</button>
      <!-- #endif -->
      <!-- #ifdef H5 -->
      <button class="bnt-wrap bnt" @click="toShare">去分享</button>
      <!-- #endif -->
    </view>
  </view>
</template>

<script lang="ts" setup>
import { onShareAppMessage, onLoad, onShow } from '@dcloudio/uni-app';
import { getActivityById, joinActivity } from '@/service/apis/market';
import { getUserId, setToastInstance, systemInfo } from '@/mixins/info';
// #ifdef H5
import nativeApi from '@/mixins/nativeApi';
// #endif
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

const $toast: any = inject('$Toast');

const originId = import.meta.env.VITE_VUE_APP_ORIGIN_ID;
const imgUrl = import.meta.env.VITE_VUE_APP_RES;
const miniEnv = import.meta.env.VITE_VUE_APP_MINI_ENV;

let heightScroll = ref(`height:${systemInfo.screenHeight - systemInfo.safeBottom - 62}px`);
// #ifdef H5
heightScroll.value = `height:${
  systemInfo.screenHeight - systemInfo.safeBottom - systemInfo.navHeight - 62
}px`;
// #endif

const data = reactive({
  id: '',
  pic: '',
  delay: 1500,
  shareSuccess: false,
});

// #ifdef MP-WEIXIN
onShareAppMessage((res): any => {
  data.shareSuccess = false;
  const promise = new Promise((resolve, reject) => {
    if (res.from === 'button') {
      if (getUserId()) {
        joinActivity(data.id)
          .then(() => {
            data.shareSuccess = true;
            resolve({
              path: `/pagesMain/shareGroup/shareGroup?id=${data.id}`,
            });
          })
          .catch(e => {
            $toast(e.msg, { duration: 2000 });
            setTimeout(() => {
              resolve({
                path: `/pagesMain/shareGroup/shareGroup?id=${data.id}`,
              });
            }, data.delay);
          });
      } else {
        resolve({
          path: `/pagesMain/shareGroup/shareGroup?id=${data.id}`,
        });
      }
    } else {
      resolve({
        path: `/pagesMain/shareGroup/shareGroup?id=${data.id}`,
      });
    }
  });
  return {
    title: '',
    path: `/pagesMain/shareGroup/shareGroup?id=${data.id}`,
    promise,
  };
});
// #endif

// #ifdef H5
const shareOption = () => {
  console.log('originId', originId);
  nativeApi.shareMiniProgram({
    appletId: originId,
    url: 'https://www.baidu.com',
    path: `/pagesMain/shareGroup/shareGroup?id=${data.id}`,
    thumbUrl: `${imgUrl}share-img.png`,
    env: miniEnv, // develop preview publish
    title: '',
    content: '',
  });
};

const toShare = () => {
  if (getUserId()) {
    joinActivity(data.id)
      .then(() => {
        data.shareSuccess = true;
        shareOption();
      })
      .catch(e => {
        $toast(e.msg, { duration: 2000 });
        setTimeout(() => {
          shareOption();
        }, data.delay);
      });
  } else {
    shareOption();
  }
};
// #endif

const getActivityDetail = () => {
  getActivityById(data.id).then((res: any) => {
    console.log('getActivityById', res);
    data.pic = res.pic;
  });
};

onLoad((option: any) => {
  data.id = option.id;
  getActivityDetail();
  const userId = getUserId();
  if (!userId) {
    uni.showModal({
      content: '活动仅限平台用户参加，请您先登录!',
      showCancel: false,
      success: (e: any) => {
        if (e.confirm) {
          uni.navigateTo({
            url: `/pages/login/login?page=/pagesMain/shareGroup/shareGroup?id=${data.id}`,
          });
        }
      },
    });
  }
});

onShow(() => {
  if (data.shareSuccess) {
    $toast('您已成功参加活动，可稍后查看券是否到账！', { duration: 2000 });
    data.shareSuccess = false;
  }
});

// #ifdef H5
const onClickLeft = () => {
  uni.navigateBack();
};
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${systemInfo.statusBarHeight}px`;
});
// #endif
</script>

<style lang="scss" scoped>
.share-group {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  box-sizing: border-box;
  bottom: constant(safe-area-inset-bottom);
  bottom: env(safe-area-inset-bottom);

  &-bg {
    position: relative;
    height: calc(100% - 62px - constant(safe-area-inset-bottom));
    height: calc(100% - 62px - env(safe-area-inset-bottom));
    overflow-y: scroll;
    background-color: #f2f2f2;
  }

  &-img {
    width: 100%;
    height: 630px;
    background-size: 100% 100%;
    background-repeat: no-repeat;
  }

  .bottom-wrap {
    position: absolute;
    display: flex;
    justify-content: space-between;
    bottom: 0;
    width: 100vw;
    height: 62px;
    padding: 0 16px;
    box-sizing: border-box;
    background-color: #ffffff;
    bottom: constant(safe-area-inset-bottom);
    bottom: env(safe-area-inset-bottom);

    .bnt {
      width: 100%;
      height: 40px;
      margin-top: 12px;
      border-radius: 50px;
    }
  }
}
</style>